package fr.alesia.deepstack.data.jdo;

import java.util.HashSet;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;

import javax.jdo.Extent;

import com.google.appengine.api.users.User;

import fr.alesia.deepstack.bean.Player;
import fr.alesia.deepstack.bean.jdo.PlayerJdo;
import fr.alesia.deepstack.data.DataAccessObject;
import fr.alesia.deepstack.data.PlayerDao;

public class PlayerDaoJdo extends AbstractDao implements DataAccessObject, PlayerDao {

	private static PlayerDao instance = null;
	
	private PlayerDaoJdo(){}
	
	public static PlayerDao getInstance(){
		if(instance == null){		
			instance = new PlayerDaoJdo();
		}
		return instance;
	}
	
	public void delete(Player player) {
		
		open();
		Player base = manager.getObjectById(PlayerJdo.class, player.getName());
		manager.deletePersistent(base);
		close();
	}

	public Player find(String id) {
		
		open();
		Player player = manager.getObjectById(PlayerJdo.class, id);
		close();
		return player;
	}

	
	public Player findByName(String name) {
		
		Set<Player> players = this.findAll();
		for (Player player : players) {
			if(player.getName().equals(name)){
				return player;
			}
		}
		return null;
	}

	public SortedSet<Player> findAll() {
		
		open();
		Set<Player> players = new HashSet<Player>(50);
	    Extent<PlayerJdo> extent = manager.getExtent(PlayerJdo.class);
	    for (Player player : extent) {
	    	players.add(player);
	    }
	    extent.closeAll();
		extent = null;
		return new TreeSet<Player>(players);
	}
	
	public Set<Player> findByUser(User user) {

		open();
		Set<Player> players = new HashSet<Player>(50);
	    Extent<PlayerJdo> extent = manager.getExtent(PlayerJdo.class);
	    for (Player player : extent) {
	    	
	    	if(player.getUser().equals(user)){
	    		players.add(player);
	    	}
	    }
	    extent.closeAll();
		extent = null;
		return players;
	}

	public void insert(Player player) {
		
		player.setId((player.getId() == null ? "k" + player.hashCode() : player.getId()));
		open();
		manager.makePersistent(player);
		close();
	}

	public void update(Player player) {
		
		open();
		Player base = manager.getObjectById(PlayerJdo.class, player.getName());
		base.setName(player.getName());
		base.setUser(player.getUser());
		manager.makePersistent(base);
		close();
	}
}
